package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.CreativeAchievement;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.CreativeAchievementService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/creativeAchievement")
public class CreativeAchievementController {

    @Autowired
    private CreativeAchievementService creativeService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询创作成果数据
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getCreativeList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            IPage<CreativeAchievement> page = new Page<>(currentPage, pageSize);
            QueryWrapper<CreativeAchievement> queryWrapper = new QueryWrapper<>();

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }

            if (params.containsKey("nameKeyword") && params.get("nameKeyword") != null && !params.get("nameKeyword").isEmpty()) {
                queryWrapper.like("creative_achievement_name", params.get("nameKeyword"));
            }
            if (params.containsKey("categoryKeyword") && params.get("categoryKeyword") != null && !params.get("categoryKeyword").isEmpty()) {
                queryWrapper.like("creative_category", params.get("categoryKeyword"));
            }
            if (params.containsKey("levelKeyword") && params.get("levelKeyword") != null && !params.get("levelKeyword").isEmpty()) {
                queryWrapper.like("creative_level", params.get("levelKeyword"));
            }
            // 模糊查询条件 - 获得时间
            if (params.containsKey("creativeYear") && params.get("creativeYear") != null && !params.get("creativeYear").isEmpty()) {
                queryWrapper.apply("YEAR(creative_year) = {0}", params.get("creativeYear"));
            }

            // 精确查询条件 - 项目提交状态
            if (params.containsKey("creativeStatus") && params.get("creativeStatus") != null && !params.get("creativeStatus").isEmpty()) {
                queryWrapper.eq("creative_status", params.get("creativeStatus"));
            }

            // 精确查询条件 - 项目审核状态
            if (params.containsKey("creativeReviewStatus") && params.get("creativeReviewStatus") != null && !params.get("creativeReviewStatus").isEmpty()) {
                queryWrapper.eq("creative_review_status", params.get("creativeReviewStatus"));
            }

            IPage<CreativeAchievement> resultPage = creativeService.getCreativeAchievementList(page, queryWrapper);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增创作成果数据
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> saveCreative(@RequestBody CreativeAchievement creativeAchievement) {
        String username = creativeAchievement.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

        // 判断该用户是否已经在 total_work 表中存在记录
//        QueryWrapper<CreativeAchievement> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        int count = creativeService.count(queryWrapper);
//
//        if (count > 0) {
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "该用户已存在，不能重复新增");
//            return ResponseEntity.badRequest().body(response);
//        } // 4. 自动计算分值
//        int baseScore = academicWorkService.getScoreByType(academicWork.getAcademicWorkCategory());
//        academicWork.setAcademicWorkScore(baseScore);
//        // 2. 计算总分值并保存到ScientificActivitySum表
//        academicWorkService.calculateTotalScore(academicWork);

        // 设置 userId 并保存
        creativeAchievement.setUserId(userId);

        int baseScore = creativeService.getScoreByType(creativeAchievement.getCreativeCategory(),creativeAchievement.getCreativeLevel());
        creativeAchievement.setCreativeScore(baseScore);
                // 2. 计算总分值并保存
//        creativeService.calculateTotalScore(creativeAchievement);

        creativeAchievement.setCreativeSubmissionTime(LocalDateTime.now());
        creativeAchievement.setCreativeStatus("已提交");
        creativeAchievement.setCreativeReviewStatus("未审核");

        creativeService.save(creativeAchievement);

        String year = null;
        if (creativeAchievement.getCreativeYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(creativeAchievement.getCreativeYear());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = creativeAchievement.getCreativeYear().substring(0, 4);
            }
        }
        if (year != null) {
            creativeService.updateTotalWorkCreativeAchievementScore(userId, year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 批量删除创作成果数据
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteCreative(@RequestBody List<Long> ids) {
        // 1. 查出所有要删的数据
        List<CreativeAchievement> toDelete = creativeService.listByIds(ids);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        for (CreativeAchievement ca : toDelete) {
            if (ca.getUserId() != null && ca.getCreativeYear() != null) {
                String year = null;
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(ca.getCreativeYear());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = ca.getCreativeYear().substring(0, 4);
                }
                userYearSet.add(ca.getUserId() + "#" + year);
            }
        }

// 3. 删除
        creativeService.removeByIds(ids);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            creativeService.updateTotalWorkCreativeAchievementScore(userId, year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改创作成果数据（修复静态方法调用和添加校验逻辑）
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateCreative(@RequestBody CreativeAchievement creativeAchievement) {
        // 1. 获取前端传递的用户名
        String username = creativeAchievement.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            creativeAchievement.setUserId(user.getUserId());
        }

        int baseScore = creativeService.getScoreByType(creativeAchievement.getCreativeCategory(),creativeAchievement.getCreativeLevel());
        creativeAchievement.setCreativeScore(baseScore);
        // 2. 计算总分值并保存
//        creativeService.calculateTotalScore(creativeAchievement);

        creativeService.updateById(creativeAchievement);

        String year = null;
        if (creativeAchievement.getCreativeYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(creativeAchievement.getCreativeYear());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = creativeAchievement.getCreativeYear().substring(0, 4);
            }
        }
        if (year != null) {
            creativeService.updateTotalWorkCreativeAchievementScore(creativeAchievement.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/review")
    public ResponseEntity<Map<String, Object>> reviewCreativeAchievement(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long creativeId = Long.valueOf(params.get("creativeId").toString());
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            CreativeAchievement creative = creativeService.getById(creativeId);
            if (creative == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            creative.setCreativeReviewStatus(reviewStatus);
            creative.setCreativeReviewTime(java.time.LocalDateTime.now());
            creative.setCreativeReviewResult(reviewResult);

            if ("审核通过".equals(reviewStatus)) {
                creative.setCreativeReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(reviewStatus)) {
                creative.setCreativeStatus("未提交");
            }

            creativeService.updateById(creative);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportCreativeAchievement(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {

        // 3. 查询 CreativeAchievement（可按年份筛选）
        QueryWrapper<CreativeAchievement> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("creative_year", year.substring(0, 4)); // 替换为你的年份字段
        }

        // 只导出审核通过的数据
        queryWrapper.eq("creative_status", "已提交");

        List<CreativeAchievement> list = creativeService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (CreativeAchievement ca : list) {
            ca.setUsername(userIdNameMap.getOrDefault(ca.getUserId(), ""));
        }

        // 5. 给每条数据加序号（如有 rowNum 字段）
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 如果有 rowNum 字段
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "创作成果类-" + now + ".xlsx";

        // 7. 导出
        ExcelExportUtil.export(response, list, CreativeAchievement.class, "创作成果", fileName);
    }

}